package com.blb.edugatewayservice.filter;

import com.blb.common.entity.User;
import com.blb.common.util.JwtUtils;
import com.blb.common.util.ResponseStatus;
import com.blb.common.util.RsaUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.jcajce.provider.asymmetric.rsa.RSAUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * 登录验证过滤器
 */
@Slf4j
@Component
public class LoginAuthenticationFilter implements GlobalFilter, Ordered {

//    //白名单
//    private List<String> whiteList = Arrays.asList("/login","/logout","/courses",
//            "/course-orientations","/course-orientations/parent/",
//            "/course-types","/search-courses","/ads");

    @Autowired
    private WhiteListConfig whiteListConfig;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获得请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //对白名单放行
        Set<String> whiteList = whiteListConfig.getWhiteList();
        for(String url : whiteList){
            String path = request.getURI().getPath();
            if(path.contains(url)){
                log.info("白名单放行:{}",path);
                //放行请求
                return chain.filter(exchange);
            }
        }
        //获得请求头
        String auth = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if(StringUtils.isEmpty(auth)){
            log.info("请求token为空，验证失败");
            //设置响应代码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //给客户端返回错误提示信息
            DataBuffer wrap = response.bufferFactory().wrap(ResponseStatus.AUTH_ERROR.getMessage().getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        //对token进行解析
        try {
            User user = JwtUtils.getUserFromToken(auth, RsaUtils.publicKey);
            log.info("token解析成功:{}",user);
            //放行请求
            return chain.filter(exchange);
        } catch (Exception e) {
            log.error("token解析失败",e);
            //设置响应代码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //给客户端返回错误提示信息
            DataBuffer wrap = response.bufferFactory().wrap(ResponseStatus.AUTH_ERROR.getMessage().getBytes());
            return response.writeWith(Mono.just(wrap));
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
